import { authApi, departmentApi } from "../../utils/api"

// 个人中心页面逻辑
Component({
  data: {
    // 用户信息
    userInfo: null,
    
    // 加载状态
    isLoading: true,
    departmentId: '',
    departmentName: '',
    
    // 数据刷新标志
    needRefresh: true
  },

  methods: {
    // 页面加载时初始化
    onLoad() {
      this.loadUserData()
      this.loadDeparmentList()
    },

    // 页面显示时刷新数据（解决tab切换不刷新问题）
    onShow() {
      // 只在需要刷新时重新加载数据，避免重复加载
      if (this.data.needRefresh) {
        this.loadUserData()
        this.loadDeparmentList()
        this.setData({ needRefresh: false })
      }
    },

    // 加载用户数据
    loadUserData() {
      try {
        const userInfo = wx.getStorageSync('userInfo')
        if (userInfo) {
          this.setData({ 
            userInfo: userInfo,
            isLoading: false,
            departmentId: userInfo.departmentId || ''
          })
        } else {
          // 用户未登录，重置数据
          this.setData({ 
            userInfo: null,
            isLoading: false,
            departmentId: '',
            departmentName: ''
          })
        }
      } catch (error) {
        console.error('加载用户数据失败:', error)
        this.setData({ 
          userInfo: null,
          isLoading: false,
          departmentId: '',
          departmentName: ''
        })
      }
    },

    async loadDeparmentList() {
      try {
        if (!this.data.departmentId) {
          this.setData({ departmentName: '' })
          return
        }

        const res = await departmentApi.getDepartmentList()
        console.log('部门列表响应:', res)
        
        if (res.code === 200 && res.data && Array.isArray(res.data)) {
          const department = res.data.find(item => item.id === this.data.departmentId)
          if (department) {
            this.setData({
              departmentName: department.name
            })
          } else {
            console.warn('未找到对应部门:', this.data.departmentId)
            this.setData({ departmentName: '未知部门' })
          }
        } else {
          console.error('获取部门列表失败:', res)
          this.setData({ departmentName: '' })
        }
      } catch (error) {
        console.error('加载部门数据失败:', error)
        this.setData({ departmentName: '' })
      }
    },

    // 退出登录
    logout() {
      wx.showModal({
        title: '确认退出',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            authApi.logout().then(res => {
              if (res.code === 200) {
                wx.hideLoading()
                wx.showToast({
                  title: '退出成功',
                  icon: 'success'
                })

                wx.removeStorageSync('userInfo')
                wx.removeStorageSync('token')

                this.setData({ 
                  userInfo: null,
                  departmentId: '',
                  departmentName: '',
                  needRefresh: true  // 重置刷新标志
                })

                wx.navigateTo({
                  url: '/pages/login/login',
                })
              }
            })
          }
        }
      })
    },
  }
})